import Esbuild from "esbuild";
import klawSync from "klaw-sync";
import { __projectDir } from "albert.gao";
import Path from "path";
import chalk from "chalk";
export function toJsPath(path) {
  return path
    .replace(/[\\/]backend[\\/]/, "/backend.js/")
    .replace(/\.ts$/, ".js");
}

export async function buildBackendFile(path) {
  let jsPath = toJsPath(path);
  if (/.[jt]s$/i.test(path)) {
    return Esbuild.build({
      entryPoints: [path],
      platform: "node",
      bundle: false,
      outfile: jsPath,
      allowOverwrite: true,
      format: "cjs",
    });
  } else {
    return "";
  }
}

export function buildAllBackend() {
  return klawSync(Path.resolve(__projectDir, "backend"), { nodir: true }).map(
    (e) => buildBackendFile(e.path)
  );
}

Promise.all(buildAllBackend())
  .then(() => {
    console.clear();
    return console.log(
      chalk.bold.greenBright(
        "--------------------  ts -> js √ --------------------"
      )
    );
  })
  .catch(console.error);
